/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.xxl.adapter.dao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.xxl.adapter.core.XxlConvert;
import com.xxl.adapter.entity.JobInfo;
import com.xxl.adapter.repository.JobInfoRepository;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import java.util.List;
import javax.persistence.criteria.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Component;

/**
 * XxlJobInfoDaoImpl
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
public class JobInfoDaoImpl implements XxlJobInfoDao, XxlConvert {

  @Autowired private JobInfoRepository repository;

  public Page<JobInfo> page(
      int offset,
      int pagesize,
      int jobGroup,
      int triggerStatus,
      String jobDesc,
      String executorHandler,
      String author) {
    return repository.findAll(
        ((root, query, cb) -> {
          Predicate predicate = cb.conjunction();
          if (jobGroup > 0) {
            predicate.getExpressions().add(cb.equal(root.get("jobGroup"), jobGroup));
          }
          if (triggerStatus >= 0) {
            predicate.getExpressions().add(cb.equal(root.get("triggerStatus"), triggerStatus));
          }
          if (StrUtil.isNotBlank(jobDesc)) {
            predicate.getExpressions().add(cb.like(root.get("jobDesc"), "%" + jobDesc + "%"));
          }
          if (StrUtil.isNotBlank(executorHandler)) {
            predicate
                .getExpressions()
                .add(cb.like(root.get("executorHandler"), "%" + executorHandler + "%"));
          }
          if (StrUtil.isNotBlank(author)) {
            predicate.getExpressions().add(cb.like(root.get("author"), "%" + author + "%"));
          }

          return predicate;
        }),
        PageRequest.of(offset, pagesize, Sort.by(CollectionUtil.newArrayList(Order.desc("id")))));
  }

  @Override
  public List<XxlJobInfo> pageList(
      int offset,
      int pagesize,
      int jobGroup,
      int triggerStatus,
      String jobDesc,
      String executorHandler,
      String author) {
    Page<JobInfo> page =
        this.page(offset, pagesize, jobGroup, triggerStatus, jobDesc, executorHandler, author);
    return this.convert(XxlJobInfo.class, page.getContent());
  }

  @Override
  public int pageListCount(
      int offset,
      int pagesize,
      int jobGroup,
      int triggerStatus,
      String jobDesc,
      String executorHandler,
      String author) {
    Page<JobInfo> page =
        this.page(offset, pagesize, jobGroup, triggerStatus, jobDesc, executorHandler, author);
    return (int) page.getTotalElements();
  }

  @Override
  public int save(XxlJobInfo xxlJobInfo) {
    JobInfo jobInfo = repository.save(this.convert(JobInfo.class, xxlJobInfo));
    // 新增失败是因为xxl又从对象中获取Id而非使用返回的Id
    xxlJobInfo.setId(jobInfo.getId());
    return jobInfo.getId();
  }

  @Override
  public XxlJobInfo loadById(int id) {
    return this.convert(XxlJobInfo.class, repository.findById(id).orElse(null));
  }

  @Override
  public int update(XxlJobInfo xxlJobInfo) {
    JobInfo jobInfo = this.convert(JobInfo.class, xxlJobInfo);
    // key 丢失导致更新作业重复创建的问题
    repository.findById(xxlJobInfo.getId()).ifPresent(x -> jobInfo.setKey(x.getKey()));

    return this.save(jobInfo);
  }

  @Override
  public int delete(long id) {
    repository.deleteById((int) id);
    return (int) id;
  }

  @Override
  public List<XxlJobInfo> getJobsByGroup(int jobGroup) {
    return this.convert(
        XxlJobInfo.class,
        repository.findAll(((root, query, cb) -> cb.equal(root.get("jobGroup"), jobGroup))));
  }

  @Override
  public int findAllCount() {
    return repository.findAll().size();
  }

  @Override
  public List<XxlJobInfo> scheduleJobQuery(long maxNextTime, int pagesize) {
    Page<JobInfo> page =
        repository.findAll(
            ((root, query, cb) ->
                cb.and(
                    cb.equal(root.get("triggerStatus"), 1),
                    cb.lessThan(root.get("triggerNextTime"), maxNextTime))),
            PageRequest.of(0, pagesize, Sort.by(Order.asc("id"))));

    return this.convert(XxlJobInfo.class, page.getContent());
  }

  @Override
  public int scheduleUpdate(XxlJobInfo xxlJobInfo) {
    int id = xxlJobInfo.getId();
    JobInfo jobInfo = repository.findById(id).orElse(null);
    if (jobInfo != null) {
      jobInfo.setTriggerLastTime(xxlJobInfo.getTriggerNextTime());
      jobInfo.setTriggerNextTime(xxlJobInfo.getTriggerNextTime());
      jobInfo.setTriggerStatus(xxlJobInfo.getTriggerStatus());

      repository.save(jobInfo);
    }

    return id;
  }

  @Override
  public Logger getLogger() {
    return log;
  }
}
